package com.andy.mall.product.exception;

import com.andy.common.exception.BizCodeEnum;
import com.andy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MallExceptionAdvance
 * @Description 异常集中处理类
 * @Auther Andy
 * @Date 2020/11/12 16:44
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice
public class MallExceptionAdvance {
    /**
     * 收集所有MethodArgumentNotValidException.class类型的异常进行处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        Map<String,String> map =new HashMap<>();
        //拿到所有异常结果
        BindingResult br=e.getBindingResult();
        br.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error(e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
